﻿using Microsoft.AspNetCore.Mvc;
using System.Drawing;
using System.Runtime.InteropServices;
using TextureGenerator.Mechanics;

namespace TextureGenerator.Controllers
{
    public class UseController : Controller
    {
        private const string outputDir = "wwwroot/output/";
        private const string tempDir = "wwwroot/tmp/";
        private const string outputDirEx = "../output/";
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Gen(GenConfig config,IFormFile? shape,int sigma)
        {
            AutoGC();
            Drawer d = new Drawer(config);

            int[,]? depth = null ;
            if (shape != null)
            {
                string tmpPath = tempDir + RandomName(shape.FileName);
                FileStream shapeTmp = System.IO.File.Open(tmpPath,FileMode.Create);
                shape.CopyTo(shapeTmp);
                shapeTmp.Dispose();
                depth = InputProcessor.Run(tmpPath, sigma ,config.GetPixel());
            }
            Bitmap map = d.Draw(depth);
            string fileName = RandomName();
            FileStream fs = System.IO.File.Open(outputDir+fileName,FileMode.Create);
            map.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
            fs.Dispose();
            return Redirect(outputDirEx + fileName);
        }
        private static void AutoGC()
        {
            if (new Random().NextSingle() < 0.9f)
                return;
            DirectoryInfo di = new DirectoryInfo(outputDir);
            var files = di.EnumerateFiles();
            foreach(var f in files)
            {
                if(DateTime.Now - f.CreationTime > TimeSpan.FromMinutes(10))
                {
                    f.Delete();
                }
            }
            DirectoryInfo di2 = new DirectoryInfo(tempDir);
            var files2 = di2.EnumerateFiles();
            foreach (var f in files2)
            {
                if (DateTime.Now - f.CreationTime > TimeSpan.FromMinutes(10))
                {
                    f.Delete();
                }
            }
        }
        private string RandomName()
        {
            return new Random().Next() + ".png";
        }
        private string RandomName(string originalName)
        {
            string suffix = originalName.Split('.')[^1];
            return new Random().Next() + "." + suffix;
        }
    }
}
